// pages/login/login.js
import { sendApplyAgentCodeAction, saveNickNameAndAvatarAction, smsLoginAction, decryptWxPhone } from "../../service/config"
// imTODO
import { updateUserImInfo } from "../../service/newIm_service"
import {
  bindingPhone
} from "../../service/jb_mine_service"
import {
  FIRST_LOGIN_HOME,
  BIND_USER_ID
} from "../../service/base_service"
import {
  voteReq,
} from "../../service/jb_activity_service"
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeStyle: "",
    navBarTitle: "登录/注册",
    formData: {
      phone: "",
      code: "",
    },
    //默认头像地址
    plaAvatarImg: "https://saas.img.ylyc.top/iconplaavatar_icon.png",
    couponCodeBtnStatus: false,
    couponCodeBtnTitle: "获取验证码",
    snsMsgWait: 60,//倒计时
    isAgreeProtocol: false,
    loginType: "", // 登录类型，有的页面跳转到登录页后，登录后是需要直接返回原页面的。
    worksId: null,
    voteId: null,
    isLogin: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.type) {
      this.setData({
        loginType: options.type
      })
    }
    if (options.type == 'vote') {
      this.setData({
        voteId: options.voteId,
        worksId: options.worksId
      })
    }
    this.getClipboardDataAction();
  },
  getClipboardDataAction() {
    wx.getClipboardData({
      success: res => {
        console.log('JJLog:获取到的剪贴板内容是：' + JSON.stringify(res));
        if (res.data != 'getClipboardDataAction' && res.data) {
          //满足这两点就试下去解码
          let str = res.data.toLowerCase();
          if (str.length === 6) {
            this.decryptNumber(str);
          }

        }
      }
    })
  },
  commonClick() {
    wx.showToast({
      title: '请先阅读并同意佳宝19用户协议和隐私协议',
      icon: "none"
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.themeStyle) {
      this.setData({
        themeStyle: app.globalData.themeStyle
      })
    }

    // console.log("JJLog:看看加密是啥：" + this.encryptNumber(11945));
    // console.log('JJLog:看看解密是====：' + this.decryptNumber('aaajh3'));
  },

  //加密方法
  encryptNumber(num) {
    // 确保数字在合理范围内
    if (num < 0 || num >= Math.pow(36, 6)) {
      throw new Error("数字超出可编码范围");
    }

    const charSet = 'abcdefghijklmnopqrstuvwxyz0123456789';
    let encryptedStr = '';

    // 循环处理直到数字为0
    while (num > 0) {
      let remainder = num % 36; // 使用36进制（26个字母+10个数字）
      encryptedStr = charSet[remainder] + encryptedStr;
      num = Math.floor(num / 36);
    }

    // 如果长度不足6位，在前面补充字符。这里以'a'为例，实际可根据需求调整
    while (encryptedStr.length < 6) {
      encryptedStr = 'a' + encryptedStr;
    }

    return encryptedStr.substring(0, 6); // 确保最终长度不超过6位
  },

  //解密方法
  decryptNumber(encryptedStr) {
    if (encryptedStr.length === 0 || encryptedStr.length > 6) {
      console.log("加密字符串长度不合法");
      return;
    }

    const charSet = 'abcdefghijklmnopqrstuvwxyz0123456789';
    let decryptedNum = 0;
    const base = 36;

    for (let i = encryptedStr.length - 1, power = 1; i >= 0; i--, power *= base) {
      const charIndex = charSet.indexOf(encryptedStr[i]);
      if (charIndex === -1) {
        console.log("JJLog:解密失败===");
        break;
      }

      decryptedNum += charIndex * power;


      //解密成功：

    }
    if (decryptedNum) {
      console.log("JJLog:解密成功========：" + decryptedNum);
      wx.setStorageSync(BIND_USER_ID, decryptedNum)
      setTimeout(() => {
        console.log('JJLOg:再尝试获取一下====：' + wx.getStorageSync(BIND_USER_ID));
      }, 3000);
    }


    return decryptedNum;
  },


  //输入绑定
  bindhidePhone(e) {
    // console.log("JJLog:e:" + JSON.stringify(e));
    let type = e.currentTarget.dataset.type;
    let changeItem = `formData.${type}`;
    this.setData({
      [changeItem]: e.detail.value
    })
  },
  /** 发送验证码 */
  clickSendCode() {
    if (this.data.couponCodeBtnStatus) {
      return;
    }
    let that = this;
    //点击了发送按钮，就先禁用掉这个按钮点击
    this.setData({
      couponCodeBtnStatus: true,
    })
    //调用发送验证码接口:
    let phone = this.data.formData.phone;
    let warn = null;
    if (phone == '') {
      warn = "号码不能为空";
    } else if (phone.trim().length != 11 || !/^1[3|4|5|6|7|8|9]\d{9}$/.test(phone)) {
      warn = "手机号格式不正确";
    } else {
      sendApplyAgentCodeAction(phone).then((data) => {
        //当手机号正确的时候提示用户短信验证码已经发送
        wx.showToast({
          title: '短信验证码已发送',
          icon: 'none',
          duration: 2000
        });
        let inter = setInterval(function () {
          this.setData({
            couponCodeBtnStatus: true,
            couponCodeBtnTitle: this.data.snsMsgWait + 's后重发',
            snsMsgWait: this.data.snsMsgWait - 1
          });
          if (this.data.snsMsgWait < 0) {
            clearInterval(inter)
            this.setData({
              couponCodeBtnTitle: '重新发送',
              snsMsgWait: 60,
              couponCodeBtnStatus: false
            });
          }
        }.bind(this), 1000);

      }).
        catch((err) => {
          that.setData({
            couponCodeBtnStatus: false
          })
          wx.showToast({
            icon: 'none',
            title: err,
          })
        })


    }
    if (warn != null) {
      wx.showModal({
        title: '提示',
        content: warn
      })
      that.setData({
        couponCodeBtnStatus: false
      })
      return;
    }

  },
  //登录下一步操作
  nextBtnAction() {
    if (!this.data.formData.phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: "none"
      })
      return;
    }
    if (!this.data.formData.code) {
      wx.showToast({
        title: '请输入验证码',
        icon: "none"
      })
      return;
    }
    if (!this.data.isAgreeProtocol) {
      wx.showToast({
        title: '请输入同意用户政策与隐私',
        icon: "none"
      })
      return;
    }

    wx.getUserProfile({
      desc: "请求您的微信头像昵称授权",
      success: res => {
        console.log("JJLog:微信授权:" + JSON.stringify(res));
        saveNickNameAndAvatarAction(res.userInfo.nickName, res.userInfo.avatarUrl)
        // imTODO
        this.updateUserImInfo(res.userInfo.nickName, res.userInfo.avatarUrl)
        wx.showLoading({
          title: '登录中',
        })
        smsLoginAction(this.data.formData).then((data) => {
          wx.hideLoading();
          if (data.code == 200) {
            wx.showToast({
              title: '登录成功'
            });
            app.globalData.isLogin = true;
            wx.setStorageSync(FIRST_LOGIN_HOME, true);
            setTimeout(() => {
              wx.switchTab({
                url: '/pages/home/home',
              })
            }, 2000)

          }
        }).catch((err) => {
          wx.hideLoading();
          wx.showToast({
            icon: 'none',
            title: err || "操作失败",
          }, 2000);

        })
      },
      fail: err => {
        console.log("JJLog:获取微信信息失败:" + JSON.stringify(err));
        wx.showToast({
          title: '授权才能登录',
          icon: "none"
        })
      }
    })



  },
  // imTODO 更新im的资料
  updateUserImInfo(name, avatar) {
    let params = {
      account: app.globalData.openId,
      name: name,
      avatar: avatar,
      appId: app.globalData.imAppId,
    }
    updateUserImInfo(params).then(res => {
      if (res.code == 200) {
        console.log("JJLog:更新IM资料成功=====");
      }
    }).catch(err => {
      console.error("JJLog:更新IM资料失败===:", err);
    })
  },

  /**
   * 协议操作
   */
  agreenAction() {
    this.setData({
      isAgreeProtocol: !this.data.isAgreeProtocol
    })
  },

  /**
   * 微信登录
   */
  getPhoneNumberWxLogin(e) {
    var decryptInfo = e.detail;
    let _this = this;
    console.log('=====phone=====: ', app.globalData.phone)
    console.log("JJLog:e===:" + JSON.stringify(e));
    let bindUserId = wx.getStorageSync(BIND_USER_ID) || null;
    console.log("JJLog:bindUserId====:" + bindUserId);
    if (e.detail.encryptedData) {
      wx.showLoading();
      wx.login({
        success: res => {
          decryptInfo.code = res.code;
          decryptInfo.type = 'routine';
          decryptInfo.spreadPid = bindUserId;
          bindingPhone(decryptInfo).then((data) => {
            wx.hideLoading();
            if (data.code == 200) {
              wx.setStorageSync("openId", data.data.token)
              // app.globalData.phone = data.data
              app.globalData.isLogin = true
              this.setData({
                isLogin: true,
              })
              wx.showToast({
                title: '登录成功'
              });
              wx.setStorageSync(FIRST_LOGIN_HOME, true);
              if (this.data.loginType == 'vote') {
                //作品投票详情来的
                setTimeout(() => {
                  this.voteAction();
                }, 300)

                setTimeout(() => {
                  wx.navigateBack();
                }, 2000)
              } else {
                app.globalData.isCanVote = true;
                setTimeout(() => {
                  wx.switchTab({
                    url: '/pages/home/home',
                  })
                }, 2000)
              }

            }
          }).catch(err => {
            wx.hideLoading();
            wx.showToast({
              title: err || "注册失败",
              icon: "none"
            })
          })
        }, fail: err => {
          console.log("JJLog:获取微信信息失败:" + JSON.stringify(err));
          wx.hideLoading();
          wx.showToast({
            title: err || "注册失败",
            icon: "none"
          })
        }
      })
    } else {
      wx.hideLoading();
      wx.showToast({
        title: '为了给您提供更好的服务,此功能需要您的授权',
        icon: 'none'
      })
    }
  },

  voteAction() {
    // console.log("JJLog:进入登录页就报这个啦：====")
    // if (!this.data.isLogin) {
    //   return;
    // }
    console.log("JJLog:登录成功后投票来了吗？====")
    voteReq({
      voteId: this.data.voteId,
      worksId: this.data.worksId,
    }).then(res => {
      if (res.code == 200) {
        console.log("JJLog:登录页-投票成功======")
        app.globalData.voteSuccess = true;
        app.globalData.isCanVote = false;
      }
    }).catch(err => {
      wx.hideLoading()
      console.error("JJLog:登录页-投票失败====voteReq:", err);
    })
  }



})